package net.joey.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

public class SequenceStreamDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
//			seperate("AFile.java",50);
			concate("AFile.java",4);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public static void seperate(String filename,int size) throws IOException{
		FileInputStream fis = new FileInputStream(filename);
		BufferedInputStream bis = new BufferedInputStream(fis);
		int count = 0;
		if(fis.available() % size == 0){
			count = fis.available()/size;
		}else{
			count = fis.available()/size + 1;
		}
		for(int i = 0;i<count;i++){
			int num = 0;
			File f = new File(filename+"_"+i);
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
			int r = -1;
			while((r = bis.read()) != -1){
				bos.write(r);
				num ++;
				if(num == size){
					bos.flush();
					bos.close();
					break;
				}else{
					bos.flush();
				}
			}
			bos.close();
		}
	}
	public static void concate(String filename,int count) throws IOException{
		FileInputStream fis = new FileInputStream(filename);
		
		List<InputStream> fiss = new ArrayList<InputStream>();
		for(int i = 0;i<count;i++){
			fiss.add(new FileInputStream(filename+"_"+i));
		}
		final Iterator<InputStream> iis = fiss.iterator();
		SequenceInputStream sis = new SequenceInputStream(new Enumeration<InputStream>(){
			@Override
			public boolean hasMoreElements() {
				return iis.hasNext();
			}

			@Override
			public InputStream nextElement() {
				return iis.next();
			}
		});
		BufferedInputStream bis = new BufferedInputStream(sis);
		File f = new File(filename+"_con");
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
		int r = -1;
		while((r = bis.read()) != -1){
			bos.write(r);
		}
		bis.close();
		bos.flush();
		bos.close();
	}

}
